﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using CVSS.Client.SC.Business.HistoryReplay;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using GISCommon.Business;
using SysCommon.Business.CVSS.WS.Query;
using SysCommon.Config;
using SysCommon.Entity.CVSS.WS.Query;
using SysCommon.Entity.CVSS.WS.Stakeout;
using SysCommon.Interface.BusinessGIS;
using AppCommon.Framework;

namespace CVSS.Client.SC.UI
{
    public partial class HistoryReplayForm : SysCommon.FrmSubParent 
    {
        public HistoryReplayForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 历史回放助手
        /// </summary>
        private HistoryReplayHelper replayHelper=null;

        private bool blnEndPlay = false;
        private bool blnOnPlay = false;

        /// <summary>
        /// 描述：窗体初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HistoryReplayForm_Load(object sender, EventArgs e)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用HistoryReplayForm_Load函数");
                /***
                //地图文件路径
               // string map_path = ConfigSettings.GetAttributeString(@"GIS_MAP_PATH");
                string map_path = Application.StartupPath + ConfigSettings.GetAttributeString(@"GIS_MAP_PATH");
                //添加地图到地图控件

                if (mapControl.CheckMxFile(map_path))
                    mapControl.LoadMxFile(map_path);
                else
                {
                    MessageBox.Show("地图文件\n" + map_path + "不存在\n加载地图发生错误，请与管理员联系！");
                }

                //索引图文件路径

                string mapIndex_path = Application.StartupPath + ConfigSettings.GetAttributeString(@"GIS_MAP_INDEX_PATH");
                //初始化地图索引控件

                mapIndex.Initial(mapControl, mapIndex_path);

                //初始化图层信息

                tocControl.Initial(mapControl);
***/  
              
                
                IBGIS_GeneralBizCtrl IBGIS = (IBGIS_GeneralBizCtrl)SystemFactory.GetBizController(typeof(IBGIS_GeneralBizCtrl));
                IBGIS.LoadMaps(mapControl);
                //工具栏初始化
                mapTools.init(mapControl);
                //初始化helper
                replayHelper=new HistoryReplayHelper(mapControl);
                replayHelper.OnPlay += new HistoryReplayHelper.ProcessHandler(replayHelper_OnPlay);
                replayHelper.EndPlay += new HistoryReplayHelper.ProcessHandler(replayHelper_EndPlay);

                //按钮处理
                btn_Play.Enabled = false;
                btn_Pause.Enabled = false;
                //dud_PlayRate.DownButton();

                SysCommon.Global.mainLog.Debug("调用HistoryReplayForm_Load函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用HistoryReplayForm_Load函数出错", ex);
            }
        }

        void replayHelper_EndPlay(CarHistory_Ety ety)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用replayHelper_EndPlay函数");
                blnEndPlay = true;
                trkBar_ReplaySpeed.Value = 0;
                btn_Play.Enabled = true;
                btn_Pause.Enabled = false;
                blnOnPlay = false;
                SysCommon.Global.mainLog.Debug("调用replayHelper_EndPlay函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用replayHelper_EndPlay函数出错", ex);
            }
        }

        void replayHelper_OnPlay(CarHistory_Ety ety)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用replayHelper_OnPlay函数");

                trkBar_ReplaySpeed.Value = replayHelper.POINTCOUNT;
                //添加信息显示
                this.txt_Area.Text = ety.POSITIONCITY;
                this.txt_Heading.Text = ety.HEADING.ToString();
                this.txt_Latitude.Text = ety.LATITUDE.ToString();
                this.txt_Longitude.Text = ety.LONGITUDE.ToString();
                this.txt_Road.Text = ety.POSITIONROAD;
                this.txt_SignalTime.Text = ety.DATEDMYTIME.ToString();
                this.txt_Speed.Text = ety.SPEED.ToString() + "km/h";
                
                SysCommon.Global.mainLog.Debug("调用replayHelper_OnPlay函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用replayHelper_OnPlay函数出错", ex);
            }
        }

        /// <summary>
        /// 描述：单击播放按钮

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Play_Click(object sender, EventArgs e)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用btn_Play_Click函数");
                blnEndPlay = false;
                btn_Pause.Enabled = true;
                btn_Play.Enabled = false;
                string txt = dud_PlayRate.Text.Trim();
                if (txt.Length == 0) txt = "1";
                if (txt == "0") txt = "1";
                replayHelper.SetPlayInterval(Convert.ToInt16(txt),blnOnPlay);
                replayHelper.StartReplay();
                blnOnPlay = true;

                SysCommon.Global.mainLog.Debug("调用btn_Play_Click函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用btn_Play_Click函数出错", ex);
            }
        }

        /// <summary>
        /// 描述：单击暂停按钮

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Pause_Click(object sender, EventArgs e)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用btn_Pause_Click函数");
                //lbl_PlayInterval.Text = "当前播放进度：0帧/" + trkBar_ReplaySpeed.Maximum + "帧";
                btn_Pause.Enabled = false;
                btn_Play.Enabled = true;
                replayHelper.PauseReplay();
                blnOnPlay = false;

                SysCommon.Global.mainLog.Debug("调用btn_Pause_Click函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用btn_Pause_Click函数出错", ex);
            }
        }

        /// <summary>
        /// 描述：进度条的值改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trkBar_ReplaySpeed_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用trkBar_ReplaySpeed_ValueChanged函数");
                if (blnEndPlay)
                {
                    lbl_PlayInterval.Text = "播放进度：0帧/" + trkBar_ReplaySpeed.Maximum + "帧";
                    return;
                }

                if (!blnOnPlay) return;

                if(trkBar_ReplaySpeed.Value!=replayHelper.POINTCOUNT)
                {
                    replayHelper.Replay(trkBar_ReplaySpeed.Value);
                }
                lbl_PlayInterval.Text = "当前播放进度：" + trkBar_ReplaySpeed.Value + "帧/"+trkBar_ReplaySpeed.Maximum+"帧";
                SysCommon.Global.mainLog.Debug("调用trkBar_ReplaySpeed_ValueChanged函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用trkBar_ReplaySpeed_ValueChanged函数出错", ex);
            }
        }

        private SysCommon.Entity.CVSS.WS.Stakeout.CarHistory_Ety[] GetCarInfos(DateTime startDT, DateTime endDT, string carPlate)
        {
            TimeSpan dlta_time = endDT - startDT;
            if (dlta_time.Minutes >= 10)
            {

            }
            SysCommon.Entity.CVSS.WS.Stakeout.CarHistory_Ety[] re_etys; 
            WS_Query_BizCtrlImpl m =new WS_Query_BizCtrlImpl();
            int id = m.GetCarID(carPlate);
            if (id == 0)
            {
                MessageBox.Show("不存在该车牌号");
                return null;
            }
            
            View_CarHistory_Ety[] etys = null;

            SysCommon.Entity.CVSS.WS.Query.QueryCondition_Ety query = new 
                SysCommon.Entity.CVSS.WS.Query.QueryCondition_Ety();
            query.BEGINDATETIME = startDT;
            query.ENDDATETIME = endDT;
            query.CARPLATE = carPlate;



            m.GetHistoryByCar2Completed += new SysCommon.Events.CVSS.WS.Query.GetHistoryByCar2CompletedEventHandler(m_GetHistoryByCar2Completed);
            //m.BeginGetHistoryByCar2(query,
            //    new AsyncCallback(this.getHistoryDatas), m);
            m.GetHistoryByCar2Async(query);
            return null;
        }

        void m_GetHistoryByCar2Completed(object sender, SysCommon.Events.CVSS.WS.Query.GetHistoryByCar2CompletedEventArgs e)
        {
            try
            {
                SysCommon.MsgBox.ProecssingMessageBox.EndProecssing();
                if (e == null)
                {
                    //下载数据失败
                    MessageBox.Show("下载数据失败，请检查网络连接。");
                    return;
                }
                CarHistory_Ety[] re_etys = null;
                byte[] bys = e.Result;
                if (bys != null)
                {
                    SysCommon.Entity.Business.View.View_CarHistory_Ety[] his = null;

                    his = SysCommon.Tools.CompressionHelper.DeCompressEntity(bys) as
                        SysCommon.Entity.Business.View.View_CarHistory_Ety[];

                    if (his != null)
                    {
                        re_etys = new CarHistory_Ety[his.Length];
                        int i = 0;
                        foreach (SysCommon.Entity.Business.View.View_CarHistory_Ety ety in his)
                        {
                            re_etys[i] = new SysCommon.Entity.CVSS.WS.Stakeout.CarHistory_Ety();
                            re_etys[i].LONGITUDE = ety.LONGITUDE;
                            re_etys[i].LATITUDE = ety.LATITUDE;
                            re_etys[i].HEADING = ety.HEADING;
                            re_etys[i].CARPLATE = ety.CARPLATE;
                            re_etys[i].DATEDMYTIME = ety.DATEDMYTIME;
                            re_etys[i].POSITIONCITY = ety.AREANAME;
                            re_etys[i].POSITIONROAD = ety.ROADNAME;
                            re_etys[i].SPEED = ety.SPEED;
                            i++;
                        }

                    }
                }
                QueryFinish(re_etys);
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用m_GetHistoryByCar2Completed出错", ex);
            }
        }

        private void QueryFinish(CarHistory_Ety[] etys)
        {
            SysCommon.MsgBox.ProecssingMessageBox.EndProecssing();
            if (etys == null || etys.Length == 0)
            {
                MessageBox.Show("对不起，没有找到对应数据！");
                return;
            }

            string carIcon = Application.StartupPath + ConfigSettings.GetAttributeString(@"GIS_ICON_PATH");
            carIcon += "policeCarBlue2.bmp";
            this.mapControl.ActiveView.GraphicsContainer.DeleteAllElements();
            this.mapControl.ActiveView.Refresh();
            replayHelper.SetCarHistoryEntity(etys);
            replayHelper.SetCarIcon(carIcon);
            replayHelper.SetPlayInterval(trkBar_ReplaySpeed.Value, blnOnPlay);
            replayHelper.Initial();
            replayHelper.DrawRoutine();

            trkBar_ReplaySpeed.Minimum = 0;
            trkBar_ReplaySpeed.Maximum = etys.Length;

            lbl_PlayInterval.Text = "播放进度：" + trkBar_ReplaySpeed.Value + "帧/" + trkBar_ReplaySpeed.Maximum + "帧";

            btn_Play.Enabled = true;
        }

        /// <summary>
        /// 描述：单击确定按钮

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_OK_Click(object sender, EventArgs e)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用btn_OK_Click函数");

                if (blnOnPlay)
                {
                    string mes="当前正在回放历史，确实要放弃本次回放吗？\r\n";
                    mes+="[是]放弃，[否]返回";
                    if (MessageBox.Show(mes, "历史回放", MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                        == DialogResult.No)
                    {
                        return;
                    }
                    else
                    {
                        btn_Pause_Click(null, null);
                    }
                }
                //获取车牌号
                if (cmbBox_CarPlate.Text.Trim() == "")
                {
                    MessageBox.Show("请输入车牌号","信息提示");
                    return;
                }
                string carPlate = cmbBox_CarPlate.Text.Trim();
                //获取时间段

                string date = dtp_StartDate.Value.ToShortDateString();
                string time = dtp_StartTime.Value.ToLongTimeString();

                DateTime dtstart = Convert.ToDateTime(string.Format("{0} {1}", date, time));

                date = dtp_EndDate.Value.ToShortDateString();
                time = dtp_EndTime.Value.ToShortTimeString();

                DateTime dtend = Convert.ToDateTime(string.Format("{0} {1}", date, time));

                SysCommon.MsgBox.ProecssingMessageBox.StartProecssing(this, "正在加载数据，请稍候...");
                Application.DoEvents();

                SysCommon.Entity.CVSS.WS.Stakeout.CarHistory_Ety[] etys = GetCarInfos(dtstart, dtend, carPlate);

                SysCommon.Global.mainLog.Debug("调用btn_OK_Click函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用btn_OK_Click函数出错", ex);
            }
        }

        /// <summary>
        /// 描述：播放速率改变时

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dud_PlayRate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                SysCommon.Global.mainLog.Debug("开始调用dud_PlayRate_TextChanged函数");
                replayHelper.SetPlayInterval(Convert.ToInt16(dud_PlayRate.Text),blnOnPlay);
                SysCommon.Global.mainLog.Debug("调用dud_PlayRate_TextChanged函数结束");
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用dud_PlayRate_TextChanged函数出错", ex);
            }
        }

        private void cmbBox_CarPlate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
                btn_OK_Click(null, null);
        }

        private void getHistoryDatas(IAsyncResult result)
        {
            try
            {
                SysCommon.MsgBox.ProecssingMessageBox.EndProecssing();

                WS_Query_BizCtrlImpl m = result.AsyncState as WS_Query_BizCtrlImpl;
                if (m != null)
                {
                    CarHistory_Ety[] re_etys = null;
                    byte[] bys = m.EndGetHistoryByCar2(result);
                    if (bys != null)
                    {
                        SysCommon.Entity.Business.View.View_CarHistory_Ety[] his = null;

                        his = SysCommon.Tools.CompressionHelper.DeCompressEntity(bys) as
                            SysCommon.Entity.Business.View.View_CarHistory_Ety[];

                        if (his != null)
                        {
                            re_etys = new CarHistory_Ety[his.Length];
                            int i = 0;
                            foreach (SysCommon.Entity.Business.View.View_CarHistory_Ety ety in his)
                            {
                                re_etys[i] = new SysCommon.Entity.CVSS.WS.Stakeout.CarHistory_Ety();
                                re_etys[i].LONGITUDE = ety.LONGITUDE;
                                re_etys[i].LATITUDE = ety.LATITUDE;
                                re_etys[i].HEADING = ety.HEADING;
                                re_etys[i].CARPLATE = this.cmbBox_CarPlate.Text.Trim();
                                re_etys[i].DATEDMYTIME = ety.DATEDMYTIME;
                                re_etys[i].POSITIONCITY = ety.AREANAME;
                                re_etys[i].POSITIONROAD = ety.ROADNAME;
                                re_etys[i].SPEED = ety.SPEED;
                                i++;
                            }

                        }
                    }
                    if (this.InvokeRequired)
                    {
                        if (_queryFinish == null)
                        {
                            _queryFinish = new QueryFinishDelegate(
                                this.QueryFinish);
                        }
                        this.Invoke(_queryFinish, new object[] {re_etys });
                        
                    }
                    else
                    {
                        QueryFinish(re_etys);
                    }
                }
            }
            catch (Exception ex)
            {
                SysCommon.Global.mainLog.Error("调用出错", ex);
            }
        }
        private QueryFinishDelegate _queryFinish;
    }
    internal delegate void QueryFinishDelegate(CarHistory_Ety[] etys);

}